package model.server;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class ConnectionHandler {
	private OutputStream out;

	private InputStreamReader in;

	private Socket socket;

	public ConnectionHandler(Socket socket) {
		try {
			this.socket = socket;
			out = socket.getOutputStream();
			in = new InputStreamReader(socket.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String readAll() {
		String line = new String();
		try {
			char b = 0;
			while ((b = (char) in.read()) != '\n') {
				line = line + b;
			}
			line = line.trim();
		} catch (IOException e) {
			e.printStackTrace();
			line = "";
		}

		return line;
	}

	public void sendAll(String response) {
		try {
			out.write((response + '\n').getBytes());
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void close() {
		try {
			in.close();
			out.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
